package linker.plugin;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.Scanner;

import javax.swing.AbstractButton;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import org.gnu.stealthp.rsslib.RSSChannel;
import org.gnu.stealthp.rsslib.RSSException;
import org.gnu.stealthp.rsslib.RSSHandler;
import org.gnu.stealthp.rsslib.RSSItem;
import org.gnu.stealthp.rsslib.RSSParser;

public class LinkTwitter extends PluginItem implements ActionListener {
	// @_@
	private static final long serialVersionUID = 1L;

	private JButton addButton = new JButton("Add");

	private AbstractButton refreshButton = new JButton("Refresh");

	private DefaultListModel listModel;

	private JList list = new JList();

	private String FRIENDSRSSURL = "http://twitter.com/statuses/friends_timeline.rss";

	private String UPDATEURL = "http://twitter.com/statuses/update.rss";

	public LinkTwitter() {
		super("LinkTwitter");
		setName("LinkTwitter");

		Container container = getContentPane();

		JPanel userPanel = new JPanel();
		addButton.addActionListener(this);
		userPanel.add(addButton);
		refreshButton.addActionListener(this);
		userPanel.add(refreshButton);
		container.add(userPanel, BorderLayout.NORTH);

		listModel = new DefaultListModel();
		list.setModel(listModel);
		container.add(new JScrollPane(list), BorderLayout.CENTER);

		setWindow();
	}

	public void create() {
		Authenticator.setDefault(new HttpBasicAuthe());
	}

	public String toString() {
		return "LinkTwitter";
	}

	public void refresh() {
		listModel.clear();

		URL url;
		try {
			url = new URL(FRIENDSRSSURL);

			RSSHandler handler = new RSSHandler();
			RSSParser.parseXmlFile(url, handler, false);
			RSSChannel ch = handler.getRSSChannel();

			LinkedList items = ch.getItems();

			for (int i = 0; i < items.size(); i++)
				listModel.addElement(((RSSItem) items.get(i)).getTitle());

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RSSException e) {
			e.printStackTrace();
		}
	}

	public void setPluginDir(String dir) {
		icon = new ImageIcon(dir + this.fileSeparator + "icon.png");

		create();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == refreshButton) {
			refresh();
		} else if (e.getSource() == addButton) {
			addItem();
		}
	}

	private void addItem() {
		String message = JOptionPane.showInputDialog("Input message");
		if (message == null)
			return;
		try {
			URL u = new URL(UPDATEURL);
			URLConnection conn = u.openConnection();
			conn.setDoOutput(true);
			PrintWriter writer = new PrintWriter(conn.getOutputStream());
			writer.print("&status=" + URLEncoder.encode(message, "UTF-8"));
			writer.close();

			Scanner in;
			StringBuilder response = new StringBuilder();
			try {
				in = new Scanner(conn.getInputStream());
			} catch (IOException e) {
				if (!(conn instanceof HttpURLConnection))
					throw e;
				InputStream err = ((HttpURLConnection) conn).getErrorStream();
				if (err == null)
					throw e;
				in = new Scanner(err);
			}
			while (in.hasNextLine()) {
				response.append(in.nextLine());
				response.append("\n");
			}

			in.close();
			System.out.println(response);

			refresh();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
